﻿CREATE FUNCTION QIC.TokenSubstitute(@Token QIC.TokenTable READONLY, @SourceToken VARCHAR(50), @TokenMap VARCHAR(50))
RETURNS VARCHAR(50)
AS
BEGIN
	DECLARE @TargetToken VARCHAR(50)

	IF ISNULL(@TokenMap,'') <> ''
	BEGIN
		SELECT @TargetToken = ThenToken
		FROM QIC.TokenMap tokenmap 
		WHERE TokenMap = @TokenMap 
		AND WhenToken = @SourceToken

		SET @TargetToken = ISNULL(@TargetToken,@SourceToken)

		IF '''' + REPLACE(@TargetToken,'''','') + '''' <> @TargetToken
		BEGIN
			IF NOT EXISTS (SELECT * FROM @Token WHERE PropertyName = @TargetToken) SET @TargetToken = NULL
		END
	END
	ELSE
	BEGIN
		SET @TargetToken = @SourceToken
		IF NOT EXISTS (SELECT * FROM @Token WHERE PropertyName = @TargetToken) SET @TargetToken = NULL
	END

	RETURN ISNULL(@TargetToken,'NULL')
END